//########################common
function refresh_ssq_xh(sbzq_dm) {

    var myDate = new Date();
    var year =  myDate.getFullYear();    //获取完整的年份(4位,1970-????)
    var month= myDate.getMonth()+1;       //获取当前月份(0-11,0代表1月)
    var day = myDate.getDate();        //获取当前日(1-31)

    var iCount = 0;
    if ("01" == sbzq_dm) {
        iCount = 12;

        if(day>15){
            month = month;
        }else{
            month = month-1;
        }

    } else if ("03" == sbzq_dm) {
        iCount = 4;

        if(month>1&&month<=3){
            month =1 ;
        }
        if(month>3&&month<=6){
            month =2 ;
        }
        if(month>6&&month<=9){
            month =3 ;
        }
        if(month>9&&month<=12){
            month =4 ;
        }
    } else if ("06" == sbzq_dm) {
        iCount = 2;

        if(month>1&&month<=6){
            month =1 ;
        }
        if(month>6&&month<=12){
            month =2 ;
        }
    } else if ("12" == sbzq_dm) {
        $("#sel_ssq_xh").combobox("clear");
        $("#sel_ssq_xh").combobox("loadData", []);
        $("#sel_ssq_xh").combobox("disable");

        // $("#txt_ssq_q").attr("disabled", "disabled");
        // $("#txt_ssq_z").attr("disabled", "disabled");
        month = 0;
    }
    // $("#txt_ssq_q").removeAttr("disabled");
    // $("#txt_ssq_z").removeAttr("disabled");
    if (iCount > 0) {
        var arr_xh = new Array();
        arr_xh.push({"code": "-1", "name":""});
        for (var i = 1; i <= iCount; i++) {
            var item = new Object();
            item.code = i;
            item.name = item.code;
            arr_xh.push(item);
        }

        $("#sel_ssq_xh").combobox("clear");
        $("#sel_ssq_xh").combobox("loadData", arr_xh);
        $("#sel_ssq_xh").combobox("enable");

    }
    if(month == 0){
        $("#sel_ssq_xh").combobox("setValue", "");
    }else{
        $("#sel_ssq_xh").combobox("setValue", month);
    }

    $("#sel_ssq_nd").val(year);

    calculateSsq();
}

function calculateSsq() {
    var ssq_q = "";
    var ssq_z = "";

    var sbzq_dm = $("#sel_sbzq").combobox("getValue");
    var ssq_nd = $("#sel_ssq_nd").val();
    var ssq_xh = $("#sel_ssq_xh").combobox("getValue");

    if ((sbzq_dm != null && sbzq_dm.length > 0 && sbzq_dm != "-1")
        && (ssq_nd != null && ssq_nd.length > 0 && ssq_nd != "-1")) {
        var nd = parseInt(ssq_nd);
        if (ssq_xh != null && ssq_xh.length > 0 && ssq_xh != "-1") {
            var xh = parseInt(ssq_xh);
            if ("01" == sbzq_dm) {
                ssq_q = formatSsq_q(nd, xh);
                ssq_z = formatSsq_z(nd, xh);
            } else if ("03" == sbzq_dm) {
                ssq_q = formatSsq_q(nd, ((xh - 1) * 3) + 1);
                ssq_z = formatSsq_z(nd, ((xh - 1) * 3) + 1 + 2);
            } else if ("06" == sbzq_dm) {
                if("1"==xh){
                    ssq_q = formatSsq_q(nd, 1);
                    ssq_z = formatSsq_z(nd, 6);
                }
                if("2"==xh){
                    ssq_q = formatSsq_q(nd, 7);
                    ssq_z = formatSsq_z(nd, 12);
                }


            }
        }

        if ("12" == sbzq_dm) {
            ssq_q = String.format("{0}-01-01", ssq_nd);
            ssq_z = String.format("{0}-12-31", ssq_nd);
        }
    }

    $("#txt_ssq_q").val(ssq_q);
    $("#txt_ssq_z").val(ssq_z);

    //申报日期
    if (ssq_z != null && ssq_z.length > 0) {
        if ("01" == sbzq_dm) {
            var ssq_z_nd = parseInt(ssq_z.substr(0, 4));
            var ssq_z_yd = parseInt(ssq_z.substr(5, 2));

            if (ssq_z_yd < 12) {
                ssq_z_yd++;
            } else {
                ssq_z_nd++;
                ssq_z_yd = 1;
            }

            ssq_z_nd = ssq_z_nd.toString();
            ssq_z_yd = ssq_z_yd.toString();

            if (ssq_z_yd.length < 2) {
                ssq_z_yd = "0" + ssq_z_yd;
            }

            var sbrq_q = String.format("{0}-{1}-01", ssq_z_nd, ssq_z_yd);
            var sbrq_z = String.format("{0}-{1}-15", ssq_z_nd, ssq_z_yd);

            $("#txt_sbrq_q").val(sbrq_q);
            $("#txt_sbrq_z").val(sbrq_z);
        }
    } else {
        $("#txt_sbrq_q").val("");
        $("#txt_sbrq_z").val("");
    }
}


function DayNumOfMonth(Year,Month) {
    var d = new Date(Year,Month,0);
    return d.getDate();
}

function formatSsq_q(year, month) {
    var s_year = year.toString();
    var s_month = month.toString();
    if (s_month.length < 2) {
        s_month = "0" + s_month;
    }

    return String.format("{0}-{1}-01", s_year, s_month);
}

function formatSsq_z(year, month) {
    var s_year = year.toString();
    var s_month = month.toString();
    if (s_month.length < 2) {
        s_month = "0" + s_month;
    }

    var iDay = DayNumOfMonth(year, month);
    var s_day = iDay.toString();
    if (s_day.length < 2) {
        s_day = "0" + s_day;
    }
    return String.format("{0}-{1}-{2}", s_year, s_month, s_day);
}
//########################common


function getTaxPerd(){
    var ssq_nd = $("#sel_ssq_nd").val();
    var ssq_xh = $("#sel_ssq_xh").combobox("getValue");
    var sbzq_dm = $("#sel_sbzq").combobox("getValue");
    var taxperd = "";
    //月度申报
    if ("01" == sbzq_dm) {
        if(ssq_xh<10){
            ssq_xh = '0'+ssq_xh;
        }
        //所属期间
        taxperd=ssq_nd+ssq_xh;
        //季度
    } else if ("03" == sbzq_dm) {
        //所属期间
        taxperd=ssq_nd+"Q"+ssq_xh;
    } else if ("06" == sbzq_dm) {
        taxperd=ssq_nd+"H"+ssq_xh;
    } else if ("12" == sbzq_dm) {
        taxperd=ssq_nd;
    }
    return taxperd;
}

function getValue() {
    var param = new Object();
    var sz_dm = $("#sel_sz").combobox("getValue");
    var sbzq_dm = $("#sel_sbzq").combobox("getValue");

    var ssq_q = $("#txt_ssq_q").val();
    var ssq_z = $("#txt_ssq_z").val();

    var array =  ssq_q.split("-");
    var  taxperdFrom = new Date(array[0], array[1]-1, array[2]);
    var array2 =  ssq_z.split("-");
    var  taxperdTo = new Date(array2[0], array2[1]-1, array2[2]);

    var sbrq_q = $("#txt_sbrq_q").val();
    var sbrq_z = $("#txt_sbrq_z").val();

    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var node ="";
    var nodes ="";
    var orgCodes = "";//数据来源用于分支机构增加
    //纳税主体Id
    var taxPayerId="";
    //台账类别
    var ldgTypeCode ="";
    var flag="";
    if(treeObj!=null){
        flag="2";//汇总保存逻辑
        //获取所有节点信息
        node = treeObj.getNodes();
        nodes = treeObj.transformToArray(node);
        var length = nodes.length-1;
        for(var i=0; i<nodes.length; i++) {
            if (i < length) {
                taxPayerId += nodes[i].code + ',';
            } else {
                taxPayerId += nodes[i].code;
            }
        }
    }else{
        flag="1";//分支保存逻辑
        taxPayerId =  $("#taxPayers").combobox("getValue");
        orgCodes = commonOrg();

    }
    //总机构设置台账，分支机构下面全部使用者套
    ldgTypeCode =  $("#ledger").combobox("getValue");;
    param.ldgTypeCode = ldgTypeCode
    //税种编码
    param.taxCode = sz_dm;
    //属期
    param.taxperd = getTaxPerd();
    //申报周期
    param.tdperdCode = sbzq_dm;
    //税种类别taxTypeCode
    param.taxperdFrom = taxperdFrom;
    param.taxperdTo = taxperdTo;
    param.taxPayerId = taxPayerId;
    param.orgCode = orgCodes;
    param.startDate = taxperdFrom;
    param.endDate = taxperdTo;
    param.flag= flag;
    param.cbid="-1";
    return param;
}
function checkInput() {
    var sz_dm = $("#sel_sz").combobox("getValue");
    if (sz_dm == null || sz_dm.length == 0 || sz_dm == "null" || sz_dm == "-1") {
        $.messager.alert('提示', '税（费）种不能为空，请选择税（费）种。', 'info',function(){});
        return false;
    }

    var sbzq_dm = $("#sel_sbzq").combobox("getValue");
    if (sbzq_dm == null || sbzq_dm.length == 0 || sbzq_dm == "null" || sbzq_dm == "-1") {
        $.messager.alert('提示', '申报周期不能为空，请选择申报周期。', 'info',function(){});
        return false;
    }

    var ssq_nd = $("#sel_ssq_nd").val();
    if (ssq_nd == null || ssq_nd.length == 0 || ssq_nd == "null" || ssq_nd == "-1") {
        $.messager.alert('提示', '所属期不能为空。', 'info',function(){});
        return false;
    }

    if (sbzq_dm != "12") {
        var ssq_xh = $("#sel_ssq_xh").combobox("getValue");
        if (ssq_xh == null || ssq_xh.length == 0 || ssq_xh == "null" || ssq_xh == "-1") {
            $.messager.alert('提示', '所属期不能为空。', 'info',function(){});
            return false;
        }
    }

    if (sbzq_dm == "03") {
        var ssq_q = $("#txt_ssq_q").val();
        if (ssq_q == null || ssq_q.length == 0) {
            $.messager.alert('提示', '所属期起不能为空。', 'info',function(){});
            return false;
        }

        var ssq_z = $("#txt_ssq_z").val();
        if (ssq_z == null || ssq_z.length == 0) {
            $.messager.alert('提示', '所属期止不能为空。', 'info',function(){});
            return false;
        }
    }

//            var ledger = $('#ledger').combobox("getValue");
//            if (ledger == null || ledger.length == 0) {
//                $.messager.alert('提示', '台账设置不能为空，请设置台账。', 'info',function(){});
//                return false;
//            }

//            //var arr = $("#tt").datagrid("getSelections");
//            var arr = $.fn.zTree.getZTreeObj("treeDemo");
//            if (arr == null || arr.length == 0) {
//                $.messager.alert('提示', '纳税主体不能为空，请选择纳税主体。', 'info',function(){});
//                return false;
//            }

    return true;
}

var setting = {
    callback: {
        onClick: zTreeOnClick

    },
    data: {
        key: {
            name: "name",
            title: ""
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: "0"
        }
    }
};


function zTreeOnClick(event, treeId, treeNode) {
    var orgCode=treeNode.id;
    params.orgCode=orgCode;
    params.taxPayerCode = treeNode.code;
    params.taxCode =$("#sel_sz").combobox("getValue");
    params.tdPerdCode =$("#sel_sbzq").combobox("getValue");
    params.taxPerd =getTaxPerd();
    params.cbid = "-1";
    $.ajax({
        type:"POST",
        url:path+"/system/declareParameter/showOriginAndLedger",
        data:params,
        dataType:"json",
        success:function callback(data){
            var analyMsg = data.returnObject;
            if (data.code=="0000") {
                if(analyMsg.orgDto!=null){
                    initGrid(analyMsg.orgDto);
                    $('#ledger').combobox('setValue', analyMsg.ledger);
                }
            } else {
                // $.messager.alert('信息',data.msg,'info',function(){});
            }
        }
    });
}

/**
 * @method      [initGrid]
 * @description [根据纳税主体查询机构得展示]
 * @author      [yangruidong]
 * @version     1.0
 * @param
 * @return
 * @exception
 * @date
 */
function initGrid(analyMsg) {

    $('#tt').treegrid({
        url: '',
        idField: 'id',
        treeField: 'id',
        toolbar: $('#tb'),
        columns: [[{
            field: "id", title: "id", align: "left", sortable: false, hidden: true, resizable: true, width: 80
        }, {
            field: "orgCode", title: "机构编码", align: "left", sortable: false, resizable: true, width: 80
        }, {
            field: "orgName", title: "机构名称", align: "left", sortable: false, resizable: true, width: 270
        }
        ]]
    });
    $("#tt").treegrid('loadData', analyMsg);
    $("#tt").treegrid('collapseAll');
}
/**
* @Method      getTaxPerd
* @Description 属期拼装
* @Author      [yangruidong]
* @Version     1.0
* @Param       
* @Return      
* @Exception   
* @Date        2017/12/22 16:15
*/
function getTaxPerd(){
    var ssq_nd = $("#sel_ssq_nd").val();
    var ssq_xh = $("#sel_ssq_xh").combobox("getValue");
    var sbzq_dm = $("#sel_sbzq").combobox("getValue");
    var taxperd = "";
    //月度申报
    if ("01" == sbzq_dm) {
        if(ssq_xh<10){
            ssq_xh = '0'+ssq_xh;
        }
        //所属期间
        taxperd=ssq_nd+ssq_xh;
        //季度
    } else if ("03" == sbzq_dm) {
        //所属期间
        taxperd=ssq_nd+"Q"+ssq_xh;
    } else if ("06" == sbzq_dm) {
        taxperd=ssq_nd+"H"+ssq_xh;
    } else if ("12" == sbzq_dm) {
        taxperd=ssq_nd;
    }
    return taxperd;
}

/**
 * @method      [addOrg]
 * @description [增加数据来源]
 * @author      [yangruidong]
 * @version     1.0
 * @param
 * @return
 * @exception
 * @date
 */
function addOrg() {

    if(!checkTaxPayer()){
        $.messager.alert("信息", "请先选择纳税主体", "info");
        return;
    }

    var cdmk = new refTree('orgTree','组织机构树');
    var object = new Object();
    var obj_node = null;
    var orgCodes="";
    try{
         obj_node = $('#tt').treegrid('getRoots');
        if(obj_node!=null){
            var length = obj_node.length-1;

            for(var i=0; i<obj_node.length; i++) {
                if (i < length) {
                    orgCodes += obj_node[i].id + ',';
                } else {
                    orgCodes += obj_node[i].id;
                }
            }
        }
    }catch (error){
    }

    cdmk.url = path+'/system/declareParameter/queryOrgByPid?orgCodes='+orgCodes;
    cdmk.parameters = object;
    cdmk.callBack = batchAddOrg;
    cdmk.singleLoad = 0;
    cdmk.selectedMulti = 1;
    cdmk.init();
    cdmk.openRef();
}


function  commonOrg() {
    var obj_node = $('#tt').treegrid('getRoots');

    var orgCodes="";
    if(obj_node!=null){
        var length = obj_node.length-1;

        for(var i=0; i<obj_node.length; i++) {
            if (i < length) {
                orgCodes += obj_node[i].orgCode + ',';
            } else {
                orgCodes += obj_node[i].orgCode;
            }
        }
    }

    return orgCodes;
}

function batchAddOrg(){
    //机构数据加载
    var zTree = $.fn.zTree.getZTreeObj('orgTree');
    var checkNodes = zTree.getCheckedNodes(true);

    var length = checkNodes.length-1;
    var orgCodes="";
    var _data ="";
    //清空列表
    $('#tt').treegrid('loadData', []);
    for(var i=0; i<checkNodes.length; i++){
        //父节点不添加
        if(checkNodes[i].pId==0){
            continue;
        }

        if(i<length){
            orgCodes += checkNodes[i].id+',';
        }else{
            orgCodes += checkNodes[i].id;
        }
        _data={"id":checkNodes[i].id,"orgCode":checkNodes[i].code,"orgName":checkNodes[i].name};
        var _parentId = 0;
        $('#tt').treegrid('append',{
            parent: _parentId,
            data: [_data]
        });
    }

    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var taxPayerCode ="";
    if(treeObj !=null){
        var nodes = treeObj.getSelectedNodes();
        taxPayerCode = nodes[0].code;
        //alert("纳税主体code:"+nodes[0].code);

        //新增数据来源，删除数据来源调用方法一样
        params.taxpayerId = orgCodes;
        params.taxCode =$("#sel_sz").combobox("getValue");
        params.tdPerdCode =$("#sel_sbzq").combobox("getValue");
        params.taxPayerCode=taxPayerCode;
        params.taxPerd =getTaxPerd();
        params.cbid = "-1";
        $.ajax({
            type:"POST",
            url:path+"/system/declareParameter/deleteOrAddOrgCodes",
            data:params,
            dataType:"json",
            success:function callback(data){
                var analyMsg = data.returnObject;
                if (data.code=="0000") {

                } else {

                }
            }
        });
    }
    
}


/**
 *
 * @param tagId 申报周期ID
 * @param taxperd 申报属期
 */
function changePerd(tagId, taxperd) {
    var perdCode = $("#" + tagId).combobox('getValue');
    if (perdCode == "00") {//按次申报
        $("#" + taxperd).off().on("focus", function () {
            WdatePicker({
                dateFmt: "yyyyMMdd",
                readOnly:true,
                onpicked:function(dp){ //点击某一日期后触发
                    //自动失去焦点，否则无法连续点击
                    this.blur();
                }
            });
        });
    } else if (perdCode == "01") {//月度申报
        $("#" + taxperd).off().on("focus", function () {
            WdatePicker({
                dateFmt: "yyyy",
                readOnly:true,
                onpicked:function(dp){ //点击某一日期后触发
                    //自动失去焦点，否则无法连续点击
                    this.blur();
                }
            });
        });
    } else if (perdCode == "03") {//季度申报
        $("#" + taxperd).off().on("focus", function () {
            WdatePicker({
                dateFmt: "yyyy",
                readOnly:true,
                onpicked:function(dp){ //点击某一日期后触发
                    //自动失去焦点，否则无法连续点击
                    this.blur();
                }
            });
        });
    } else if (perdCode == "06") {//半年申报
        $("#" + taxperd).off().on("focus", function () {
            WdatePicker({
                dateFmt: "yyyy",
                readOnly:true,
                onpicked:function(dp){ //点击某一日期后触发
                    //自动失去焦点，否则无法连续点击
                    this.blur();
                }
            });
        });
    } else if (perdCode == "12") {//年度申报
        $("#" + taxperd).off().on("focus", function () {
            WdatePicker({
                dateFmt: "yyyy",
                readOnly:true,
                onpicked:function(dp){ //点击某一日期后触发
                    //自动失去焦点，否则无法连续点击
                    this.blur();
                }
            });
        });
    }
}

function yearChange(){
    calculateSsq();
}